-module(signalpoint).
-behaviour(gen_server).
-include("network.hrl").
-export([start/1,start_link/1,init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).

start(Address) ->
	gen_server:start(?MODULE, [Address], []).
start_link(Address) ->
	gen_server:start_link(?MODULE,[Address],[]).
init([Address]) ->
	{ok,#sp_state{state=initiated,address=Address,type=undetermined}}.

handle_call({msg,{Role,send}},_,State) when State#sp_state.type =:= undetermined ->
  {reply,Role,State#sp_state{send_sig_num = State#sp_state.send_sig_num + 1,type = Role}};

handle_call({msg,{Role,recv}},_,State) when State#sp_state.type =:= undetermined ->
  {reply,Role,State#sp_state{recv_sig_num = State#sp_state.recv_sig_num + 1,type = Role}};

handle_call({msg,{Role,send}},_,State) when (State#sp_state.type =:= Role) or (Role =:= undetermined) ->
  {reply,State#sp_state.type,State#sp_state{send_sig_num = State#sp_state.send_sig_num + 1 }};

handle_call({msg,{Role,recv}},_,State) when (State#sp_state.type =:= Role) or (Role =:= undetermined) ->
  {reply,State#sp_state.type,State#sp_state{recv_sig_num = State#sp_state.recv_sig_num + 1 }};

handle_call({msg,{Role,send}},_,State) when State#sp_state.type =/= Role ->
  {reply,Role,State#sp_state{send_sig_num = State#sp_state.send_sig_num + 1,conflict_num = State#sp_state.conflict_num + 1}};

handle_call({msg,{Role,recv}},_,State) when State#sp_state.type =/= Role ->
  {reply,Role,State#sp_state{recv_sig_num = State#sp_state.recv_sig_num + 1,conflict_num = State#sp_state.conflict_num + 1}};

handle_call({msg,{undetermined,recv}},_,State) ->
  {reply,undetermined,State#sp_state{send_sig_num = State#sp_state.recv_sig_num + 1 }};
handle_call(get,_,State) ->
  {reply,State,State};
handle_call(_,_,State) ->
	{reply, {error,"no func define"}, State}.
handle_cast(_, State) ->
	{noreply,State}.
handle_info(_, State) ->
	{noreply,State}.
terminate(_, _) ->
	ok.
code_change(_, State, _) ->
	{ok,State}.
